package com.zyk.scaffold.core.config.exception;

import com.alibaba.fastjson.JSON;
import com.zyk.scaffold.common.basic.BasicException;
import com.zyk.scaffold.core.domain.Result;
import com.zyk.scaffold.common.enums.CommonErrorCodeEnum;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.ServletException;
import java.util.Map;

public class LocalServletErrorAttributes extends DefaultErrorAttributes {
    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
        Throwable error = getError(webRequest);
        if (error != null) {
            while (error instanceof ServletException && error.getCause() != null) {
                error = error.getCause();
            }
        }
        if (error != null) {
            Result<Object> result = null;
            if (error instanceof BasicException) {
                result = Result.error((BasicException) error);
            }else if (error instanceof Exception) {
                result = Result.error(CommonErrorCodeEnum.SERVER_ERROR);
            }
            if (result != null){
//                StringWriter stackTrace = new StringWriter();
//                error.printStackTrace(new PrintWriter(stackTrace));
//                stackTrace.flush();
//                result.setStack(RandomStringUtils.randomAlphanumeric(10) + Base64.getEncoder().encodeToString(stackTrace.toString().getBytes(StandardCharsets.UTF_8)));
                return JSON.parseObject(JSON.toJSONString(result)).getInnerMap();
            }
        }
        return super.getErrorAttributes(webRequest, options);
    }
}
